using Microsoft.AspNetCore.Mvc;
using community.Models;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authorization;
using community.Data;
using System.Security.Claims;

namespace community.Controllers
{
    /// <summary>
    /// 用户查询参数
    /// </summary>
    public class UserQueryDTO
    {
        /// <summary>
        /// 用户名关键词
        /// </summary>
        public string? Username { get; set; }

        /// <summary>
        /// 角色
        /// </summary>
        public string? Role { get; set; }

        /// <summary>
        /// 每页显示数量，默认10条
        /// </summary>
        [Range(1, 100)]
        public int PageSize { get; set; } = 10;

        /// <summary>
        /// 当前页码，默认第1页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageNumber { get; set; } = 1;
    }

    /// <summary>
    /// 更新用户角色请求模型
    /// </summary>
    public class UpdateUserRoleDTO
    {
        /// <summary>
        /// 角色
        /// </summary>
        [Required(ErrorMessage = "角色不能为空")]
        [RegularExpression("^(User|Admin)$", ErrorMessage = "角色必须是 User 或 Admin")]
        public string Role { get; set; }
    }

    /// <summary>
    /// 用户管理接口（仅管理员可用）
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize(Roles = "Admin")]
    public class UserManagementController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public UserManagementController(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取用户列表（支持分页和条件筛选）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>用户列表和总数</returns>
        /// <response code="200">成功获取用户列表</response>
        /// <response code="401">未授权</response>
        /// <response code="403">无权访问</response>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        public async Task<IActionResult> GetUsers([FromQuery] UserQueryDTO query)
        {
            var users = _context.Users.AsQueryable();

            if (!string.IsNullOrEmpty(query.Username))
                users = users.Where(u => u.Username.Contains(query.Username));

            if (!string.IsNullOrEmpty(query.Role))
                users = users.Where(u => u.Role == query.Role);

            var total = await users.CountAsync();

            var pagedUsers = await users
                .Skip((query.PageNumber - 1) * query.PageSize)
                .Take(query.PageSize)
                .Select(u => new
                {
                    u.Id,
                    u.Username,
                    u.FullName,
                    u.Email,
                    u.Role,
                    u.CreatedAt,
                    u.UpdatedAt
                })
                .ToListAsync();

            return Ok(new
            {
                Total = total,
                Items = pagedUsers
            });
        }

        /// <summary>
        /// 更新用户角色
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="dto">角色信息</param>
        /// <returns>更新结果</returns>
        /// <response code="200">成功更新用户角色</response>
        /// <response code="400">更新数据无效</response>
        /// <response code="401">未授权</response>
        /// <response code="403">无权访问</response>
        /// <response code="404">指定ID的用户不存在</response>
        [HttpPut("{id}/role")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdateUserRole(int id, UpdateUserRoleDTO dto)
        {
            var user = await _context.Users.FindAsync(id);
            if (user == null)
                return NotFound();

            // 防止管理员修改自己的角色
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            if (id == currentUserId)
                return BadRequest("不能修改自己的角色");

            user.Role = dto.Role;
            user.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(new { Message = "角色更新成功" });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>删除结果</returns>
        /// <response code="204">成功删除用户</response>
        /// <response code="401">未授权</response>
        /// <response code="403">无权访问</response>
        /// <response code="404">指定ID的用户不存在</response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        [ProducesResponseType(StatusCodes.Status403Forbidden)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteUser(int id)
        {
            var user = await _context.Users.FindAsync(id);
            if (user == null)
                return NotFound();

            // 防止管理员删除自己
            var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
            if (id == currentUserId)
                return BadRequest("不能删除自己的账号");

            _context.Users.Remove(user);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
} 